//
//  fingerPrintViewController.m
//  WZEfengAndEtong
//
//  Created by 李旭 on 16/7/20.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "fingerPrintViewController.h"
#import "Masonry.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "MBProgressHUD+WZ.h"
#import "CAccountModel.h"
#import "CAccountMgr.h"
@interface fingerPrintViewController ()
@property (nonatomic,weak)UIImageView *fingerImageView;
@property (nonatomic,weak)UILabel * noticeLabel;
@property (nonatomic,weak)UIButton *openButton;
@property (nonatomic,strong) CAccountModel *currentUser;
@end

@implementation fingerPrintViewController

-(CAccountModel *)currentUser
{
    if (_currentUser == nil) {
        _currentUser = [[[CAccountMgr alloc]init] getRecentlyLoginAccount];
    }
    return _currentUser;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationItem setNewTitleCenter:@"指纹设置"];
    UIImageView *imageView = [[UIImageView alloc]init];
    imageView.image = [UIImage imageNamed:@"fin"];
    [self.view addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(100);
        make.width.height.mas_equalTo(100);
        make.centerX.mas_equalTo(self.view);
    }];
    self.fingerImageView = imageView;
    UILabel *label = [[UILabel alloc]init];
    label.text = @"指纹密码仅对本机有效";
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor grayColor];
    [self.view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(imageView).mas_equalTo(60);
        make.width.mas_equalTo(200);
        make.height.mas_equalTo(40);
        make.centerX.mas_equalTo(self.view);
    }];
    self.noticeLabel = label;
    UIButton *button = [[UIButton alloc]init];
    BOOL ret = [USER_DEFAULT boolForKey:self.currentUser.userName];
    [button setTitle:ret?@"关闭指纹":@"开启指纹" forState:UIControlStateNormal];
    button.backgroundColor = RGBCOLOR(44, 170, 253);
    [self.view addSubview:button];
    [button addTarget:self action:@selector(changeFingerState:) forControlEvents:UIControlEventTouchUpInside];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(label).mas_equalTo(60);
        make.width.mas_equalTo(200);
        make.height.mas_equalTo(40);
        make.centerX.mas_equalTo(self.view);
    }];
    self.openButton = button;
}
-(void)changeFingerState:(UIButton*)button
{
      __weak typeof (self) weakself = self;
    BOOL ret = [USER_DEFAULT boolForKey:self.currentUser.userName];
    if (!ret) {
        LAContext* context = [[LAContext alloc] init];
        context.localizedFallbackTitle = @"";
        NSString* result = @"请验证您的指纹以开启指纹密码";
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:result reply:^(BOOL success, NSError *error) {
            if (success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [USER_DEFAULT setBool:!ret forKey:self.currentUser.userName];
                    [USER_DEFAULT synchronize];
                    BOOL ret = [USER_DEFAULT boolForKey:self.currentUser.userName];
                    if (ret) {
                         [weakself.openButton setTitle:ret?@"关闭指纹":@"开启指纹" forState:UIControlStateNormal];
                        [MBProgressHUD showSuccess:@"开启成功"];
                    }
                   
                    
                });
                
            }
            else
            {
                switch (error.code) {
                    case LAErrorSystemCancel:
                    {
                        NSLog(@"Authentication was cancelled by the system");
                        //切换到其他APP，系统取消验证Touch ID
                        break;
                    }
                    case LAErrorUserCancel:
                    {
                        NSLog(@"Authentication was cancelled by the user");
                        //用户取消验证Touch ID
                        break;
                    }
                    case LAErrorUserFallback:
                    {
                        NSLog(@"User selected to enter custom password");
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            //用户选择输入密码，切换主线程处理
                        }];
                        break;
                    }
                    default:
                    {
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            //其他情况，切换主线程处理
                        }];
                        break;
                    }
                }
            }
        }];

    }
    else
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定关闭指纹密码？" message:@"关闭指纹密码会降低安全性" preferredStyle:UIAlertControllerStyleAlert];
       
        UIAlertAction *actionYes = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [USER_DEFAULT setBool:!ret forKey:self.currentUser.userName];
            [USER_DEFAULT synchronize];
            BOOL ret = [USER_DEFAULT boolForKey:self.currentUser.userName];
            if (!ret) {
                [weakself.openButton setTitle:ret?@"关闭指纹":@"开启指纹" forState:UIControlStateNormal];
                [MBProgressHUD showSuccess:@"关闭成功"];
            }
        }];
        
        
        UIAlertAction *actionNo = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"NO");
        }];
    
        [alert addAction:actionNo];
        [alert addAction:actionYes];
        [self presentViewController:alert animated:YES completion:nil];
       

    }
}
@end
